package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    // 这次使用string数据类型来保存对象数据
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    // 引入redis缓存类
    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 判断x和y是否存在
        if (x == null || y == null) {
            // 不存在则进行普通的分页查询
            // 不需要坐标查询，按数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 存在,需要进行按距离查找
        // 设置分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // search查找,同时需要分页参数 -- 需要对应的具体距离
        // 这里只能先获取前end个数据,再进行截取,获取from ~ end 的部分
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs()
                                .limit(end)
                                .includeDistance());
        if (results == null) {
            // 如果为空返回空集合
            return Result.ok(Collections.emptyList());
        }

        // 提取id和distance
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();

        if (list.size() <= from) {
            // 没有下一页了,结束
            return Result.ok(Collections.emptyList());
        }

        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        // 截取from ~ end 的部分
        list.stream().skip(from).forEach(result -> {
            // 获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });

        // 根据id查找商铺shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD( id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 返回商铺
        return Result.ok(shops);
    }


    @Override
    public Result queryById(Long id) {
        //缓存穿透
//        Shop shop = queryWithPassThrough(id);
//        Shop shop = cacheClient
//                .queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //互斥锁解决缓存击穿
//        Shop shop = queryWithMutex(id);

        // 逻辑过期解决缓存击穿
//        Shop shop = queryWithLogicalExpire(id);
        Shop shop = cacheClient
                .queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        if (shop == null) {
            return Result.fail("商铺不存在!");
        }
        // 返回
        return Result.ok(shop);
    }


    // 创建线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //封装方法---使用逻辑过期解决缓存击穿
    // 方法内不需要有缓存穿透相关的更改
    public Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 根据id从Redis中查询商铺缓存
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        // 如果查询不到热点数据(事实上热点数据我们设置永不过期,查询不到代表参数等有误)
        if (StrUtil.isBlank(shopJSON)) {
            // 存在则直接返回
            return null;
        }
        // 命中缓存,判断缓存是否过期
        RedisData redisData = JSONUtil.toBean(shopJSON, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        if (expireTime.isAfter(LocalDateTime.now())) {
            // 未过期,直接返回商铺信息
            return shop;
        }
        // 过期,则尝试获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            // 获取锁成功应该再次判断缓存是否过期
            if (JSONUtil.toBean(stringRedisTemplate.opsForValue().get(key), RedisData.class)
                    .getExpireTime().isAfter(LocalDateTime.now())) {
                // 未过期,直接返回商铺信息
                return JSONUtil.toBean(
                        (JSONObject) JSONUtil.toBean
                                (stringRedisTemplate.opsForValue().get(key), RedisData.class).getData()
                        , Shop.class);
            }
            // 若还是过期则构建缓存
            // 获取成功,开启独立线程,进行数据更新即Redis写入,设置逻辑过期时间
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //重建缓存
                    this.saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    unlock(lockKey);
                }
            });
        }
        // 不管未获取成功还是成功获取互斥锁,直接返回商铺数据
        return shop;
    }


    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        //查询店铺数据
        Shop shop = getById(id);
        // 模拟重建的延时
        Thread.sleep(200);
        //封装店铺数据和逻辑过期事件
        RedisData data = new RedisData();
        data.setData(shop);
        data.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入Redis
        // 这个作为逻辑过期的键,不需要设置真正的TTL
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(data));

    }

    //封装方法---使用互斥锁解决缓存击穿
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 根据id从Redis中查询商铺缓存
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJSON)) {
            // 存在则直接返回
            return JSONUtil.toBean(shopJSON, Shop.class);
        }
        //如果shopJSON是""则返回空
        if (shopJSON != null) {
            return null;
        }

        // 申请互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean tryLock = tryLock(lockKey);
            if (!tryLock) {
                // 申请失败则休眠,之后再重试
                Thread.sleep(50);
                queryWithMutex(id);
            }
            // 锁申请成功要再次判断是否有缓存,有则直接返回
            // 封装方法判断
            shop = getShopCache(key);
            if (shop != null) {
                return shop;
            }

            // 没有则去数据库申请并写入
            // 申请成功则去数据库查找并写入Redis,最后返回
            shop = getById(id);
            // 模拟重建的延时
            Thread.sleep(200);

            // 数据库也不存在就返回错误信息---缓存穿透相关
            if (shop == null) {
                // 不存在则返回空值
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 数据库存在就将数据写入Redis中
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 最后释放互斥锁
            unlock(lockKey);
        }
        return shop;
    }


    //封装方法---解决缓存穿透
    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 根据id从Redis中查询商铺缓存
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJSON)) {
            // 存在则直接返回
            return JSONUtil.toBean(shopJSON, Shop.class);
        }
        //如果shopJSON是""则返回空
        if (shopJSON != null) {
            return null;
        }

        // 不存在则去数据库中查找
        Shop shop = getById(id);
        // 数据库也不存在就返回错误信息
        if (shop == null) {
            // 不存在则返回空值
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 数据库存在就将数据写入Redis中并返回
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    //获取缓存
    public Shop getShopCache(String key) {
        String cacheJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(cacheJson)) {
            // 存在则直接返回
            return JSONUtil.toBean(cacheJson, Shop.class);
        }
        //不存在则返回null
        return null;
    }


    //获取互斥锁----使用setNx实现,设置TTL是避免服务器宕机导致锁无法释放
    public boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "locked", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //释放互斥锁----让其他线程可以获取得到数据库的数据,避免同一时段请求的数量过多
    public void unlock(String key) {
        stringRedisTemplate.delete(key);
    }


    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("该商铺不存在");
        }
        // 先操作数据库
        updateById(shop);
        // 再删除Redis缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
